package com.icinfo.cloud.provider.common.utils;

import com.icinfo.cloud.provider.common.constant.Constant;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * 描述：Spring上下文工具类
 *
 * @author XiangYuYu
 * @date 2021/11/3 2:50 PM
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {

        SpringContextUtil.applicationContext = applicationContext;
        //获取环境
        Environment environment = applicationContext.getEnvironment();
        //这个获取的是配置的运行环境，如开发，测试，以及生产
        String[] activeProfiles = environment.getActiveProfiles();
        //这个获取的是当前项目默认的运行环境，一般设置为开发
        String[] defaultProfiles = environment.getDefaultProfiles();

    }

    /**
     * 描述：校验发布环境是否为生产环境
     *
     * @return boolean （true-是/false-否）
     * @author XiangYuYu
     * @date 2021/11/05
     */
    public static boolean checkIsPrdProfile() {
        String[] profiles = getActiveProfiles();
        boolean flag = false;
        if (!ObjectUtils.isEmpty(profiles) && Constant.PROFILES_PRD.equalsIgnoreCase(profiles[0])) {
            flag = true;
        }
        return flag;
    }

    /**
     * 描述：校验发布环境是否为开发环境
     *
     * @return boolean （true-是/false-否）
     * @author XiangYuYu
     * @date 2021/11/05
     */
    public static boolean checkIsDevProfile() {
        String[] profiles = getActiveProfiles();
        boolean flag = false;
        if (!ObjectUtils.isEmpty(profiles) && (Constant.PROFILES_DEV.equalsIgnoreCase(profiles[0]) || Constant.PROFILES_TEST.equalsIgnoreCase(profiles[0]))) {
            flag = true;
        }
        return flag;
    }

    /**
     * 描述：获取当前服务激活环境
     *
     * @return 当前服务激活环境
     * @author XiangYuYu
     * @date 2021/11/03
     */
    public static String[] getActiveProfiles() {
        return applicationContext.getEnvironment().getActiveProfiles();
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return applicationContext.getBean(name, requiredType);
    }

    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    public static boolean isSingleton(String name) {
        return applicationContext.isSingleton(name);
    }

    public static Class<? extends Object> getType(String name) {
        return applicationContext.getType(name);
    }

}
